package com.song.demo06springbootdata.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.apache.catalina.filters.WebdavFixFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;

//http://localhost:8888/druid  访问druid数据源监控页面
@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }

    // 后台监控  相当于web.xml
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");

        // 后台需要有人登录，账号密码配置
        HashMap<String, String> initParameters = new HashMap<>();
        // 增加配置
        initParameters.put("loginUsername","admin"); // key是固定的，loginUsername loginPassword
        initParameters.put("loginPassword","123456");
        // 允许谁可以访问：所有人都能访问
        initParameters.put("allow","");
        // 禁止谁能访问 initParameters.put("songdami","192.168.52.49");

        bean.setInitParameters(initParameters); // 设置初始化参数
        return bean;
    }

    // 过滤功能  过滤掉不要druid帮你统计的东西,不是像登陆那种过滤
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();

        bean.setFilter(new WebStatFilter());
        // 可以过滤哪些请求？
        HashMap<String, String> initParameters = new HashMap<>();
        // 这些东西不需要统计
        initParameters.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParameters);

        return bean;
    }
}
